<template>
  <el-dialog
    class="assign-role"
    title="分配角色"
    :visible="showRoleDialog"
    :close-on-click-modal="false"
    @close="closebox"
    @open="openbox"
  >
    <!-- 这里准备复选框 -->
    <!-- v-model 里边收集的是label的值 -->
    <!-- 如果checkbox中不写内容 n那么默认展示label的值 -->
    <el-checkbox-group v-model="roleIds" v-loading="loading">
      <el-checkbox v-for="item in list" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <el-button type="primary" size="small" @click="clickSubmit">确定</el-button>
      <el-button size="small" @click="closebox">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRuleListAPI } from '@/api/settings'
import { getUserAPI2 } from '@/api/user'
import { assignRolesAPI } from '@/api/employees'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      roleIds: [], // 收集选中的值, 也可以给他赋值进行回显
      list: [], // 保存所有的角色信息数据
      loading: false
    }
  },
  methods: {
    // 关闭弹框的方法
    closebox() {
      this.$emit('update:showRoleDialog', false)
    },
    // 获取所有角色信息渲染复选框
    async getRuleList() {
      const { data } = await getRuleListAPI(1, 9999)
      this.list = data.rows
    },
    async getUser() {
      const { data } = await getUserAPI2(this.userId)
      // console.log(data.roleIds)
      this.roleIds = data.roleIds
    },
    // 打开弹框的时候执行
    openbox() {
      this.loading = true
      Promise.all([this.getRuleList(), this.getUser()]).then(() => {
        this.loading = false
      })
    },
    // 点击确定 发送请求
    async clickSubmit() {
      await assignRolesAPI({
        id: this.userId,
        roleIds: this.roleIds
      })
      this.closebox()
      this.$message.success('修改员工角色信息成功')
    }
  }
}
</script>
<style lang="scss" scoped>
.assign-role {
  ::v-deep {
    .el-checkbox {
      font-size: 30px;
    }
  }
}
</style>
